import React, {useState, useEffect, useContext, useRef,createContext} from 'react';
import { Modal, Table, Input, Button, Popconfirm, message, Form, Badge } from 'antd';
import { OrgTypeItem } from '../data.d';
import FirstOrgListComponent from './FirstOrgListComponent';
import { getOrgTypeList, updateOrgType, addOrgType, delOrgType } from '../service';
import styles from '../index.less';

interface EditableRowProps {
  index: number;
}

// const EditableContext: React.Context<any> = createContext({});
const EditableContext = React.createContext<any>();

const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

interface EditableCellProps {
  title: React.ReactNode;
  editable: boolean;
  selectable:boolean;
  children: React.ReactNode;
  dataIndex: string;
  record: OrgTypeItem;
  handleSave: (record: OrgTypeItem) => void;
  handleRefresh: (refresh: boolean) => void;
}

const EditableCell: React.FC<EditableCellProps> = ({
  title,
  editable,
  selectable,
  children,
  dataIndex,
  record,
  handleSave,
  handleRefresh,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef();
  const form = useContext(EditableContext);
  
  useEffect(() => {
    if (editing) {
      inputRef.current?.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({ [dataIndex]: record[dataIndex] });
  };
  //编辑
  const updateOrgTypeCommand = (param:OrgTypeItem) => {
    new Promise((resolve, reject) => {
      updateOrgType(param)
        .then((res) => {
          if (res.code === 200) {
            message.success('保存成功');
            setEditing(false);
            handleRefresh(true);
            resolve(true);
          }else {
            message.error('保存失败：'+res.message);
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('保存失败');
          reject(error);
        });
    });
  }
  //添加
  const addOrgTypeCommand = (param:OrgTypeItem) => {
    new Promise((resolve, reject) => {
      addOrgType(param)
        .then((res) => {
          if(res){
            if (res.code === 200) {
              message.success('添加成功');
              setEditing(false);
              handleRefresh(true);
              resolve(true);
            }else {
              message.error('保存失败：'+res.message);
              resolve(false);
            }
          }
        })
        .catch((error) => {
          message.error('保存失败');
          reject(error);
        });
    });
  }

  //失去焦点后保存
  const save = async (e:Event) => {
    const values = await form.validateFields();
    const param = new Object();
    param["orgTypeName"] = values.orgTypeName;
    param["topOrgId"] = values.topOrgId;
    if(record.id){ //编辑
      param["id"] = record.id;
      updateOrgTypeCommand(param);
    }else{//添加
      addOrgTypeCommand(param);
    }
  };

  let childNode = children;
  if (editable) {
    childNode = editing ? (
      <Form.Item form={form}
        style={{ margin: 0 }}
        name={dataIndex}
        rules={[
          {
            required: true,
            max:8,
            message: `${title}不能为空并且最长8为字符`,
          },
        ]}
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
      childNode[1] ? (
        <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={toggleEdit}>
          {children}
        </div>
      ):(//默认添加显示输入框
        <Form.Item form={form}
          style={{ margin: 0 }}
          name={dataIndex}
          rules={[
            {
              required: true,
              max:8,
              message: `${title}不能为空并且最长8为字符`,
            },
          ]}
        >
          <Input ref={inputRef} onPressEnter={save} onBlur={save} />
        </Form.Item>
      )
      
    );
  }
  
  if(selectable){
    const disabled = record.isUsed;
    const topOrgId = record.topOrgId;
    form.setFieldsValue({topOrgId:topOrgId});
    childNode = (
      <Form.Item form={form}
        style={{ margin: 0 }}
        name="topOrgId"
        rules={[
          {
            required: true,
            message: '所属机构不能为空',
          },
        ]}>
          <FirstOrgListComponent 
            init={true}
            disabled={disabled} 
            defaultvalue={topOrgId}
            selectChange={
              (value) => {
                form.setFieldsValue({topOrgId:value});
                form.validateFields().then(save);
              }
            }
          >
          </FirstOrgListComponent>
      </Form.Item>)
  }
  return <td {...restProps}>{childNode}</td>;
};


interface CreateFormProps {
  modalVisible: boolean;
  onCancel: () => void;
  onSubmit: () => void;
}

const dateFormat = (fmt:string, date:Date) => {
  let ret;
  const opt = {
      "Y+": date.getFullYear().toString(),        // 年
      "m+": (date.getMonth() + 1).toString(),     // 月
      "d+": date.getDate().toString(),            // 日
      "H+": date.getHours().toString(),           // 时
      "M+": date.getMinutes().toString(),         // 分
      "S+": date.getSeconds().toString()          // 秒
      // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (let k in opt) {
      ret = new RegExp("(" + k + ")").exec(fmt);
      if (ret) {
          fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
      };
  };
  return fmt;
}

const OrgTypeModel: React.FC<CreateFormProps> = (props) => {
  const { modalVisible, onSubmit, onCancel } = props;
  const [refresh, handleRefresh] = useState<boolean>(false);
  const [loading, handleLoading] = useState<boolean>(false);
  const [dataSource, setDataSource] = useState<OrgTypeItem[]>([]);//数据源
  const [count, setCount] = useState<number>(0);//数据条数

  const setScroll = (height:number) => {
    setTimeout(function(){
      const body = document.getElementsByClassName("orgTypeTable")[0].querySelector(".ant-table-body");
      const content = body?.querySelector("table");
      if(body && content){
        body.scrollTop = height;
      }
    },0)
  }

  const getData = () =>{
    setDataSource([]);
    new Promise((resolve, reject) => {
      // 初始化table数据
      getOrgTypeList()
        .then((res) => {
          if (res && res.code === 200) {
            const list = res.data;
            for(let i in list){
              list[i].key = i;
              list[i].index = parseInt(i)+1;
              list[i].updateDatetime = dateFormat("YYYY-mm-dd HH:MM:SS", new Date(list[i].updateDatetime));
            }
            setDataSource(list);
            setCount(list.length);
            resolve(true);
            setScroll(0);
          } else {
            message.error('请求失败');
            resolve(false);
          }
          handleLoading(false);
          handleRefresh(false);
        })
        .catch((error) => {
          message.error('请求失败');
          reject(error);
        });
    });
  }

  useEffect(() => {
    if(modalVisible){
      handleLoading(true);
      getData();
    }
    
  },[modalVisible]);

  useEffect(() => {
    if(refresh){
      handleLoading(true);
      getData();
    }
  },[refresh]);

  const handleDelete = (id:number) => {
    return new Promise((resolve, reject) => {
      delOrgType(id)
        .then((res) => {
          if(res){
            if (res.code === 200) {
              message.success('删除成功');
              handleRefresh(true);
              resolve(true);
            }else if(res.code === 4501){
              message.error('该类型在使用中，暂不可删除');
              resolve(false);
            }else if(res.code === 4502){
              message.error('参数有误,数据不存在');
              resolve(false);
            }else {
              message.error('删除失败，'+ res.message);
              resolve(false);
            }
          }
        })
        .catch((error) => {
          message.error('删除失败');
          reject(error);
        });
    });
  };
  
  const handleSave = row => {
    const newData = [...dataSource];
    const index = newData.findIndex(item => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    setDataSource(newData);
  };

  const columns1 = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'number',
      width:50,
    },
    {
      title: '机构类型名称',
      dataIndex: 'orgTypeName',
      editable: true,
      width:150,
    },
    {
      title: '所属机构',
      dataIndex: 'topOrgName',
      selectable: true,
    },
    {
      title: '状态',
      dataIndex: 'isUsed',
      valueType: 'boolean',
      width:80,
      render: (isUsed:boolean) => (
        <>
         {isUsed?(<span><Badge status="processing" />使用中</span>):(<span><Badge status="default" />未使用</span>)}  
        </>
      )
    },
    {
      title: '更新时间',
      dataIndex: 'updateDatetime',
      valueType: 'dateTime',
      width:150,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width:80,
      render: (_, record:OrgTypeItem) =>
        record.orgTypeName ? (
          <Popconfirm title="是否删除？" onConfirm={() => handleDelete(record.id)}>
            <a disabled={record.isUsed?true:false}>删除</a>
          </Popconfirm>
        ) : null,
    },
  ];

  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };

  const columns = columns1.map(col => {
    if (!col.editable && !col.selectable) {
      return col;
    }
    return {
      ...col,
      onCell: (record:OrgTypeItem) => ({
        record,
        editable: col.editable,
        selectable:col.selectable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave: handleSave,
        handleRefresh:handleRefresh,//控制刷新列表
      }),
    };
  });

  const handleAdd = () => {
    const newData = {
      key: count,
      index: count+1,
      orgTypeName: '',
      text: '未使用',
      updateDatetime: '',
    };

    setDataSource([...dataSource, newData]);
    setCount(count+1);
    const height = (count+1)*49;
    setScroll(height);
    setTimeout(function(){//点击添加后默认设定焦点
      document.getElementsByClassName(styles.OrgTypeModel)[0]?.querySelector(".ant-input")?.focus();
    },200);
  };

  const renderContent = () => {
    return (
      <>
        <div>
          <Button 
            onClick={handleAdd} 
            type="primary" 
            style={{ marginBottom: 16,marginRight:5,verticalAlign:"middle" }}
          >添加
          </Button>
          <Table
            className="orgTypeTable"
            size="small"
            components={components} //覆盖默认的 table 元素
            rowClassName={() => 'editable-row'}
            bordered
            dataSource={dataSource}
            columns={columns}
            pagination={false}
            loading={loading}
            scroll={{y:240}}
          />
        </div>
      </>
      )
    }
    
  return (
    <Modal
      className={styles.OrgTypeModel}
      destroyOnClose
      maskClosable={true}
      width={800}
      title="机构类型管理"
      visible={modalVisible}
      onCancel={() => onCancel()}
      footer={[
        <Button key="back" onClick={onSubmit}>
          关闭
        </Button>
      ]}
    >
      {renderContent()}
    </Modal>
  );
};

export default OrgTypeModel;
